<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;
use App\Game;
use App\GameError;
use Qiniu\Auth as QAuth;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');

    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        if(Auth::user()->role != 'developer'){
            return redirect('/');
        }

        $games = Game::all();
        return view('home', ['games' => $games]);
    }

    public function edit($id)
    {
        if(Auth::user()->role != 'developer'){
            return redirect('/');
        }

        $accessKey = 'pLUeVMerlovNCXpD7o8SNQAy2V6tEpF3lZmvMIQ8';
        $secretKey = 'Dk4t4en4uSfKX2lphfUHQ0clWIjIxvXIoTUy6QMi';
        // 初始化签权对象
        $auth = new QAuth($accessKey, $secretKey);
        $bucket = 'bjbest';
        // 生成上传Token
        $token = $auth->uploadToken($bucket);
        $game = Game::find($id);
        return view('edit', ['game' => $game, 'token' => $token]);
    }

    public function store($id, Request $request)
    {
        if(Auth::user()->role != 'developer'){
            return redirect('/');
        }

        $game = Game::where('id', $id)->update($request->all());

        return redirect('/edit/' . $id);
    }

    public function error()
    {
        if(Auth::user()->role != 'developer'){
            return redirect('/');
        }

        $errors = GameError::take(200)->orderBy('id', 'desc')->get();
        return view('error', ['errors' => $errors ]);
    }
}
